package matt.design;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
 
/**
 * This class determines what happens when various buttons on the Homepage page are
 * clicked and the linking screens.
 * 
 * @author Crunch Time
 * @version 1.0
 */
public class HomepageActivity extends Activity {
	private Context cont = this;
	public static String CURRENT_USER;
	public static TasksDataSource datasource;
	public static ArrayAdapter<Item> adapter;
	private List<Item> values;
	private ListView lv;
	private AlertDialog alert, alert2;
	private AlertDialog.Builder builder, builder2;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.layout.homepage_menu, menu);
	    return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.menu_add:      startActivity(new Intent(getApplicationContext(), AddTaskActivity.class));
	                            	 break;
	        case R.id.menu_edit:     editItem();
	                            	 break;
	        case R.id.menu_delete:   deleteItem();
	                            	 break;
	        case R.id.menu_complete: completeItem();
	        						 break;
	        case R.id.menu_filter:	 filter();
	        						 break;
	        case R.id.menu_maps:	 startActivity(new Intent(getApplicationContext(), ViewTasksActivity.class));
	        						 break;
	    }
	    return true;
	}
	@Override
	/**
	 * Displays the homepage depending on the currenlty logged in User. When opened, the homepage
	 * will list all of the the user's tasks initally sorted by due date.
	 * 
	 * @param savedInstanceState
	 */
	public void onCreate(Bundle savedInstanceState) {
		builder = new AlertDialog.Builder(this);
		builder2  = new AlertDialog.Builder(this);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		super.onCreate(savedInstanceState);
		// setting default screen to homepage.xml
		setContentView(R.layout.homepage);
		
		datasource = new TasksDataSource(this);
		datasource.open();
		
		TextView user = (TextView) findViewById(R.id.homepage_user);
		user.setText(CURRENT_USER);
		
		values = null;
		try {
			values = datasource.getAllItems(CURRENT_USER);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		lv = (ListView) findViewById(R.id.taskList);
		adapter = new ArrayAdapter<Item>(this, R.layout.item_listview, values);
		lv.setAdapter(adapter);
		lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		adapter.notifyDataSetChanged();
		
		ImageButton addTask = (ImageButton) findViewById(R.id.btn_add_task);
		Button logoutUser = (Button) findViewById(R.id.btn_logout);
		//Button filter = (Button) findViewById(R.id.filter);
		//final Button functions = (Button) findViewById(R.id.functions);
		
		//Listener for the functions Button
		
//		functions.setOnClickListener(new View.OnClickListener() {
//			
//			/**
//			 * When the functions button clicked a single choice dialog is opened, giving the user
//			 * the option to select "Delete", "Edit", or "Completed". If "Delete" is selected then
//			 * the currently selected task will be deleted. If "Edit" then the user will be taken to
//			 * the Edit Task screen and will be able to edit the item that as currently selected.
//			 * If "Completed" is selected then the currently selected item is marked as completed.
//			 * 
//			 * @param View v
//			 */
//			public void onClick(View v) {
//				final String[] items = {"Delete", "Edit", "Completed"};
//				builder.setTitle(" ");
//				builder.setCancelable(false);
//				builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
//				    public void onClick(DialogInterface dialog, int item) {
//				    	if(items[item] == "Delete"){
//				    		//Get and call delete method
//			        		deleteItem();
//			        		
//				    	}
//				    	//Gets the checked item and opens the edit activity
//					    else if(items[item] == "Edit"){
//					    	editItem();
//					    }
//				    	//Gets the checked item and marks it as completed
//					    else if(items[item] == "Completed"){
//					    	completeItem();
//					    }
//				    	dialog.dismiss();
//				    }
//				});
//				builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
//					public void onClick(DialogInterface dialog, int which) {
//						dialog.cancel();						
//					}
//				});
//				AlertDialog alert = builder.create();
//				alert.show();
//			}
//		});
//		
//		filter.setOnClickListener(new View.OnClickListener() {
//			
//			/**
//			 * When the flter button clicked a single choice dialog is opened, giving the user
//			 * the option to select "Due Date", "Group", or "Completed". The user's list of tasks
//			 * will be filtered to a list of tasks that meet the selected filter criteria.
//			 * 
//			 * @param View v
//			 */
//			public void onClick(View v) {
//				filter();
//			}
//		});
		
		addTask.setOnClickListener(new View.OnClickListener() {
			
			/**
			 * Takes the user to the Add Task screen.
			 * 
			 * @paramt View v
			 */
			public void onClick(View v) {
				startActivity(new Intent(getApplicationContext(), AddTaskActivity.class));
			}
		});
		
		logoutUser.setOnClickListener(new View.OnClickListener() {

			/**
			 * Logouts the current user.
			 * 
			 * @param v
			 */
			public void onClick(View v) {
				CURRENT_USER = "";
				finish();
			}
		});
	}
	
		private DatePickerDialog.OnDateSetListener chooseDateListener = new DatePickerDialog.OnDateSetListener() {
	        public void onDateSet(DatePicker view, int year2, int month2, int day2) {
	        	String date = (month2+1) + "-" + day2 + "-" + year2;
	        	month2 += 1;
	        	values = null;
    			try {
    				values = datasource.getAllItems(CURRENT_USER);
    			} catch (ParseException e) {
    				e.printStackTrace();
    			}
    			//Testing: prints out the date wanted, all of the due dates names and then the values that are being put in the listview
    			System.out.println("Wanted: " + date);
    			List<Item> val = null;
    			try {
					val = datasource.getAllItems(CURRENT_USER);
				} catch (ParseException e) {
					e.printStackTrace();
				}
    			for(Item g:val){
    				System.out.println(g.getDueDate() + " ");
    			}
    			System.out.println(values);
    			
    			lv = (ListView) findViewById(R.id.taskList);
    			adapter.clear();
    			for(Item i:values){
    				String[] iDate = i.getDueDate().split("-");
    				System.out.println("Task Date: " + iDate);
    				int month = Integer.parseInt(iDate[0]);
    				int day = Integer.parseInt(iDate[1]);
    				int year = Integer.parseInt(iDate[2]);
    				System.out.println(month + ":" + month2 + " " + day + ":" + day2 + " " + year + ":" + year2);
    				if(year >= year2){
    					if(year>year2){ //year is greater therefore after
    						adapter.add(i);
    					}
    					else if(month >= month2){
    						if(month > month2){ //year is = and month is greater, therefore after
    							adapter.add(i);
    						}
    						else if(day >= day2){ //day is either greater or = so show it
    							adapter.add(i);
    						}
    					}
    				}
    			}
    			lv.setAdapter(adapter);
    			lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    			lv.clearChoices();  
	        }
	    };

	    public void editItem(){
	    	if(lv.getCheckedItemPosition() != -1) {
	    		int index = lv.getCheckedItemPosition();
    			System.out.println(index);
    			Item task = (Item) adapter.getItem(index);
    			EditTaskActivity.currentTask = task;
    			startActivity(new Intent(getApplicationContext(), EditTaskActivity.class));
	    	}
	    }
	    
	    public void deleteItem(){
			final AlertDialog.Builder checkDelete = new AlertDialog.Builder(this);
	    	checkDelete.setTitle("Are you sure?");
	    	checkDelete.setCancelable(false);
	    	checkDelete.setNegativeButton("Cancel",  new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
	    	checkDelete.setPositiveButton("Yes",  new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (lv.getCheckedItemPosition() != -1) {
			    			int index = lv.getCheckedItemPosition();
			    			Item task = (Item) adapter.getItem(index);
			    			datasource.deleteTask(task);
			    			
			    			values = null;
			    			try {
			    				values = datasource.getAllItems(CURRENT_USER);
			    			} catch (ParseException e) {
			    				e.printStackTrace();
			    			}
			    			lv = (ListView) findViewById(R.id.taskList);
			    			adapter.clear();
			    			for(Item i:values){
			    				adapter.add(i);
			    			}
			    			lv.setAdapter(adapter);
			    			lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			    			lv.clearChoices();
			    		} 
					}
			});
	    	AlertDialog deleted = checkDelete.create();
	    	deleted.show();
	    }
	    
	    public Item[] sortByDate(Item[] array) {
			if(array != null && array.length > 1){
				int min;
				for(int i = 0; i < array.length; i++){
					min = i;
					for(int j = i+1; j < array.length; j++){
						if(array[j].compareDate(array[min]) < 0){
							min = j;
						}
					}
					if(min != i){
						//swap
						Item swap = array[i];
						array[i] = array[min];
						array[min] = swap;
					}
				}
			}
			return array;
		}
	    
	    public void filter(){
	    	final String[] items = {"After Date" ,"Due Date", "Group", "Completed","Uncompleted","Show All"};
			builder.setTitle("Filter By");
			builder.setCancelable(false);
			builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
			    public void onClick(DialogInterface dialog, int item) {
			    	//if's for selection
			    	if(items[item].equals("After Date")){
			    		alert.dismiss();
			    		final Calendar c = Calendar.getInstance();
			            int year = c.get(Calendar.YEAR);
			            int month = c.get(Calendar.MONTH);
			            int day = c.get(Calendar.DAY_OF_MONTH);
			            Dialog date = new DatePickerDialog(cont, chooseDateListener, year, month, day);
			    		date.show();
			    	}
			    	else if(items[item].equals("Due Date")){
			    		values = null;
	        			try {
	        				values = datasource.getAllItems(CURRENT_USER);
	        			} catch (ParseException e) {
	        				e.printStackTrace();
	        			}
	        			lv = (ListView) findViewById(R.id.taskList);
	        			adapter.clear();
	        			
	        			Item[] items = new Item[values.size()];
	        			for(int i = 0; i < values.size(); i++){
	        				items[i] = values.get(i);
	        			}
	        			items = sortByDate(items);
	        			
	        			for(Item i:items){
	        				adapter.add(i);
	        			}
	        			lv.setAdapter(adapter);
	        			lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
	        			lv.clearChoices();
			    	}
			    	else if(items[item] == "Group"){
			    		alert.dismiss();
			    		builder2.setTitle("Filter By");
			    		builder2.setCancelable(false);
			    		System.out.println("NEW DIALOG");
			    		//if Group is selected then we want to override the current dialog and "drop down" the group choices
			    		//This string overrides the current singleChoiceItems and sets new listener
			    		final String[] groupChoices = {"Group","   -Default", "   -School", "   -Personal", "   -Work"};
			    		builder2.setSingleChoiceItems(groupChoices, -1, new DialogInterface.OnClickListener() {
							//Going to execute filter if a group is chosen if anything else (i.e. another filter) than we will jump to the previous dialog
			    			public void onClick(DialogInterface dialog, int choice) {
								if(groupChoices[choice].equals("   -Default") || groupChoices[choice].equals("   -School") || groupChoices[choice].equals("   -Personal") || groupChoices[choice].equals("   -Work")){
									//Getting just the group name and not the "   -"
									String[] group = groupChoices[choice].split("-");
									values = null;
				        			try {
				        				values = datasource.getAllOfGroup(CURRENT_USER, group[1]);
				        			} catch (ParseException e) {
				        				e.printStackTrace();
				        			}
				        			//Testing: prints out the group wanted, all of the goup names and then the values that are being put in the listview
				        			System.out.println(group[1]);
				        			List<Group> val;
				        			val = datasource.getAllGroups();
				        			for(Group g:val){
				        				System.out.print(g.getName());
				        			}
				        			System.out.println(values);
				        			
				        			//Changing the listview
				        			lv = (ListView) findViewById(R.id.taskList);
				        			adapter.clear();
				        			for(Item i:values){
				        				adapter.add(i);
				        			}
				        			lv.setAdapter(adapter);
				        			lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
				        			lv.clearChoices();	
								}
								else{
									System.out.println("NOTHING: " + items[choice]);
								}
								dialog.dismiss();
							}
						});
			    		builder2.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								dialog.cancel();						
							}
			    		});
			    		alert2 = builder2.create();
			    		alert2.show();
			    	}
			    	else if(items[item].equals("Completed")){
			    		values = null;
	        			try {
	        				values = datasource.getAllCompletedItems(CURRENT_USER);
	        			} catch (ParseException e) {
	        				e.printStackTrace();
	        			}
	        			lv = (ListView) findViewById(R.id.taskList);
	        			adapter.clear();
	        			for(Item i:values){
	        				adapter.add(i);
	        			}
	        			lv.setAdapter(adapter);
	        			lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
	        			lv.clearChoices();
			    	}
			    	else if(items[item].equals("Uncompleted")){
			    		values = null;
	        			try {
	        				values = datasource.getAllUncompletedItems(CURRENT_USER);
	        			} catch (ParseException e) {
	        				e.printStackTrace();
	        			}
	        			lv = (ListView) findViewById(R.id.taskList);
	        			adapter.clear();
	        			for(Item i:values){
	        				adapter.add(i);
	        			}
	        			lv.setAdapter(adapter);
	        			lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
	        			lv.clearChoices();
			    	}
			    	else if(items[item].equals("Show All")){
			    		values = null;
	        			try {
	        				values = datasource. getAllItems(CURRENT_USER);
	        			} catch (ParseException e) {
	        				e.printStackTrace();
	        			}
	        			lv = (ListView) findViewById(R.id.taskList);
	        			adapter.clear();
	        			for(Item i:values){
	        				adapter.add(i);
	        			}
	        			lv.setAdapter(adapter);
	        			lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
	        			lv.clearChoices();
			    	}
			    	dialog.dismiss();
			    }
			});
			builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();						
				}
			});
			alert = builder.create();
			alert.show();
	    }
	    
	    public void completeItem(){
	    	if(lv.getCheckedItemPosition() != -1) {
	    		int index = lv.getCheckedItemPosition();
	    		Item task = (Item) adapter.getItem(index);
	    		task.setCompleted(true);
	    		//check to see if it is a recurring task. If so create another task with same info but later due date
	    		if(!task.getRecurring().equals("Once")){
	    			String recurring = task.getRecurring();
	    			String dueDate = task.getDueDate();
	    			String startDate = task.getStartDate();
	    				    			
	    			
	    			if(recurring.equals("Weekly")){
	    				SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
	    				Calendar c = Calendar.getInstance();
	    				Calendar c2 = Calendar.getInstance();
	    				try {
	    					c.setTime(sdf.parse(dueDate));
	    					c2.setTime(sdf.parse(startDate));
	    				} catch (ParseException e) {
	    					e.printStackTrace();
	    				}
	    				c.add(Calendar.DATE, 7);  // number of days to add
	    				c2.add(Calendar.DATE, 7);
	    				dueDate = sdf.format(c.getTime());  // dt is now the new date
	    				startDate = sdf.format(c2.getTime());
	    				
	    						    			
	    				try {
							Item item = HomepageActivity.datasource.createTask(task.getItemName(), task.getDesc(), dueDate, startDate, 
									task.getPriority(), task.getItemGroup().toString(), recurring, false, task.getAddress(), task.getLatitude(), task.getLatitude());
							adapter.add(item);
	    				} catch (ParseException e) {
							e.printStackTrace();
						}
	    			}
	    			else if(recurring.equals("Monthly")){
	    				SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
	    				Calendar c = Calendar.getInstance();
	    				Calendar c2 = Calendar.getInstance();
	    				try {
	    					c.setTime(sdf.parse(dueDate));
	    					c2.setTime(sdf.parse(startDate));
	    				} catch (ParseException e) {
	    					e.printStackTrace();
	    				}
	    				c.add(Calendar.MONTH, 1);  // number of days to add
	    				c2.add(Calendar.MONTH, 1);
	    				dueDate = sdf.format(c.getTime());  // dt is now the new date
	    				startDate = sdf.format(c2.getTime());
	    				
	    						    			
	    				try {
							Item item = HomepageActivity.datasource.createTask(task.getItemName(), task.getDesc(), dueDate, startDate, 
									task.getPriority(), task.getItemGroup().toString(), recurring, false, task.getAddress(), task.getLatitude(), task.getLatitude());
							adapter.add(item);
	    				} catch (ParseException e) {
							e.printStackTrace();
						}
	    			}
	    			else if(recurring.equals("Yearly")){
	    				SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
	    				Calendar c = Calendar.getInstance();
	    				Calendar c2 = Calendar.getInstance();
	    				try {
	    					c.setTime(sdf.parse(dueDate));
	    					c2.setTime(sdf.parse(startDate));
	    				} catch (ParseException e) {
	    					e.printStackTrace();
	    				}
	    				c.add(Calendar.YEAR, 1);  // number of days to add
	    				c2.add(Calendar.YEAR, 1);
	    				dueDate = sdf.format(c.getTime());  // dt is now the new date
	    				startDate = sdf.format(c2.getTime());
	    				
	    						    			
	    				try {
							Item item = HomepageActivity.datasource.createTask(task.getItemName(), task.getDesc(), dueDate, startDate, 
									task.getPriority(), task.getItemGroup().toString(), recurring, false, task.getAddress(), task.getLatitude(), task.getLatitude());
							adapter.add(item);
	    				} catch (ParseException e) {
							e.printStackTrace();
						}
	    			}
	    		}
	    		datasource.updateTask(task);
	    		adapter.remove(task);
	    		
	    	}
	    }
	@Override
	protected void onResume() {
		datasource.open();
		super.onResume();
	}

	@Override
	protected void onPause() {
		datasource.close();
		super.onPause();
	}
}